<template>
    <view v-if="!editVisable">
        <BasicNavbar title="个人资料" :canBack="true" />
        <!-- 头像区域 -->
        <view :class="'flex between item-center infoItem'">
            <button open-type="chooseAvatar" class="user-avatar flex between item-center" type="balanced" @chooseavatar="onChooseavatar">
                <view class="flex item-center" >
                    <text class="labelStyle" style="text-align: start;">头像</text>
                    <image :src="getTx"  style="width: 120rpx; height: 120rpx;border-radius: 50%;" />
                </view>
                <view>
                    <u-icon name="arrow-right"></u-icon>
                </view>
            </button>
        </view>
        <!-- 其他字段 -->
        <view v-for="item, i in fieldArr" :key="item.text" :class="'flex between item-center infoItem'"
            :style="{ marginBottom: i == 2 ? '20rpx' : '' }" @click="() => onHandleUser(item)">
            <view class="flex  item-center" >
                <text class="labelStyle">{{ item.text }}</text>
                <text >{{  formDate.studentInfo[item.dataIndex] || "--" }}</text>
            </view>
            <view>
                <u-icon name="arrow-right"></u-icon>
            </view>
        </view>
        <!-- 下拉列表 -->
        <u-picker :show="showSelect && showSelect !== 0" :columns="selectData" keyName="value" @confirm="confirmSelect"
            @cancel="this.showSelect = 0" confirm-color="#37B874"></u-picker>
        <!-- 时间选择框 -->
        <u-datetime-picker
			ref="datetimePicker"
			:show="calendarVisable"
			mode="date"
            v-model="birthday"
			:formatter="formatter"
            @cancel="calendarVisable = false"
            @confirm="onSelectTime" 
            :min-date="-1451692800000"
            :max-date="Number(new Date())"
            confirm-color="#37B874"
        ></u-datetime-picker>
        <!-- <u-calendar :show="calendarVisable" @close="calendarVisable = false" @confirm="onSelectTime" ></u-calendar> -->
    </view>
    <view v-else class="editWrap">
        <BasicNavbar :title="editText" :canBack="false" :isCustomBack="true" @cancel="editVisable=false"/>
        <view class="myInputWrap">
            <view :style="{padding: '24rpx 30rpx', border: '1rpx solid #F0F0F0', borderRadius: '12rpx'}">
            <input v-model="editInputData" style="height: 24px; flex:1; margin-left: 20rpx" :maxlength="editDataIndex=='name'?15:-1" :type="editDataIndex=='nickName'?'nickname':'text'"/>
        </view>
        <view v-if="editDataIndex=='name'" class="flex between" style="color: #999999; font-size: 24rpx;padding: 10rpx">
            <text>{{editInputData.length  }}/15</text>
            <text>今日修改次数：{{formDate.modifyNameCount||0}}</text>
        </view>
        </view>
        <view class="flex between item-center">
            <text @click="editVisable=false">取消</text>
            <view class="editBtn" @click="onSumitInput">确定</view>
        </view>
    </view>
</template>

<script>
import { contraction } from "@/utils/PrjUtils";
import moment from "moment"
import {mapDictCodes} from '../../services/ServerService.js'
import {getSysPerson,updatePhoto,updateSysPerson} from "../../services/UserInfoService.js";
import { getArrObjectByProperty, notificationFun } from "../../utils/PrjUtils.js";
export default {
    data() {
        return {
            fieldArr: [
                // { text: "头像", dataIndex: "ac", type: "img" },
                { text: "姓名", dataIndex: "name" },
                { text: "昵称", dataIndex: "nickName" },
                {
                    text: "性别",
                    dataIndex: "sex",
                    type: "select",
                    dict: "ApExamineeSex",
                    showSelect: 1
                },
                {
                    text: "民族",
                    dataIndex: "nation",
                    type: "select",
                    dict: "SsPersonNationDict",
                    showSelect: 2
                },
                // { text: "手机号码", dataIndex: "phone" },
                { text: "证件号码", dataIndex: "cardId" },
                {
                    text: "出生日期",
                    dataIndex: "birthday",
                    type: "time",

                },
                {
                    text: "文化程度",
                    dataIndex: "education",
                    type: "select",
                    dict: "PersonEducation",
                    showSelect: 3
                },
            ],
            fileBase64: "",
            // 0是关闭
            showSelect: 0,
            // 下拉数据源
            selectData: [],
            // 时间选择器
            calendarVisable: false,
            // 后端数据源
            formDate: {
              
            },
            // 生日
            birthday:Number(new Date()),
            // 编辑模式
            editVisable: false,
            // 编辑字段
            editInputData: "",
            // 编辑题目
            editText:"",
            // 编辑的字段
            editDataIndex:"",
            // dict
            dict:{},
        }
    },
    methods: {
        //初始化dict
        onGetDict(){
            mapDictCodes('PersonEducation,SsPersonNationDict,ApExamineeSex ').then(res => {
				this.dict = res
			})
        },
        // 获取人员信息
        onGetUserInfo(){
            getSysPerson().then(res=>{
                let obj={...res}
                let newLoginData=uni.getStorageSync('loginData')||{}
                uni.setStorageSync('loginData',{...newLoginData,... res.studentInfo});
                obj.studentInfo.sex=obj.studentInfo.sex?getArrObjectByProperty(this.dict?.ApExamineeSex,"code",obj.studentInfo.sex)?.value:"--";
                obj.studentInfo.nation=obj.studentInfo.nation?getArrObjectByProperty(this.dict?.SsPersonNationDict,"code",obj.studentInfo.nation)?.value:"--";
                obj.studentInfo.education=obj.studentInfo.education?getArrObjectByProperty(this.dict?.PersonEducation,"code",obj.studentInfo.education)?.value:"--";
                this.birthday=obj.studentInfo.birthday?Number(new Date(obj.studentInfo.birthday)):Number(new Date())
                this.formDate=obj;
            })
        },
        // 个人操作
        onHandleUser(record) {
            switch (record.type) {
                case "img":
                    // this.onSelectImage()
                    break;
                case "select":
                    this.showSelect = record.showSelect
                    this.selectData = [this.dict[record.dict]||[]]
                    this.editDataIndex=record.dataIndex
                    break;
                case "time":
                    this.calendarVisable = true
                    break;
                default:
                    console.log(record,"--109")
                    this.editInputData = this.formDate.studentInfo[record.dataIndex] ?? ""
                    this.editText = record.text
                    this.editDataIndex=record.dataIndex
                    // console.log("111")
                    this.editVisable = true
                    break;
            }
        },
        // 上传头像
        onSelectImage() {
            // 选择文件
            uni.chooseMedia({
                count: 1, // 默认9
                mediaType: ['image'],
                sizeType: ['original', 'compressed'],
                sourceType: ['album'],
                success: (res) => {
                    const url = res.tempFiles[0].tempFilePath;
                    console.log(url,"---172")
                    // 获取文件名
                    const fileName = url.substring(url.lastIndexOf('/') + 1);
                    // 获取文件管理器
                    const fileSystemManager = uni.getFileSystemManager()
                    // 读取图片信息
                    fileSystemManager.getFileInfo({
                        filePath: url,
                        success: res => {
                            // 大于4M启用压缩
                            if ((res.size / 1024 / 1024) > 4) {
                                wx.getImageInfo({
                                    src: url,
                                    success: (cRes) => {
                                        console.log(cRes, 'res')
                                        let imgInfo = {
                                            type: cRes.type,
                                            height: cRes.height,
                                            width: cRes.width,
                                            path: cRes.path
                                        }
                                        contraction(imgInfo, 'myCanvas', this).then(newUrl => {
                                            let base64 = 'data:image/jpeg;base64,' + fileSystemManager.readFileSync(newUrl.tempFilePath, 'base64');
                                            this.onUpdatePhoto(base64,fileName)
                                            // this.formValue.photoData = 'data:image/jpeg;base64,' + fileSystemManager.readFileSync(newUrl.tempFilePath, 'base64');
                                        })
                                    },
                                    fail(err) {

                                    }
                                })
                            } else {
                                let base64='data:image/jpeg;base64,' + fileSystemManager.readFileSync(url, 'base64');
                                this.onUpdatePhoto(base64,fileName)
                                // 大小符合
                                // this.formValue.photoData = 'data:image/jpeg;base64,' + fileSystemManager.readFileSync(url, 'base64');
                                // this.fileBase64 = 'data:image/jpeg;base64,' + fileSystemManager.readFileSync(url, 'base64');
                                
                            }
                        },
                    })
                }
            })
        },
        // 选择头像
        onChooseavatar(e) {
            // console.log(e, "头像信息")
            const url = e.detail.avatarUrl;
            console.log(url, "---172")
            // 获取文件名
            const fileName = url.substring(url.lastIndexOf('/') + 1);
            // 获取文件管理器
            const fileSystemManager = uni.getFileSystemManager()
            // 读取图片信息
            fileSystemManager.getFileInfo({
                filePath: url,
                success: res => {
                    // 大于4M启用压缩
                    if ((res.size / 1024 / 1024) > 4) {
                        wx.getImageInfo({
                            src: url,
                            success: (cRes) => {
                                console.log(cRes, 'res')
                                let imgInfo = {
                                    type: cRes.type,
                                    height: cRes.height,
                                    width: cRes.width,
                                    path: cRes.path
                                }
                                contraction(imgInfo, 'myCanvas', this).then(newUrl => {
                                    let base64 = 'data:image/jpeg;base64,' + fileSystemManager.readFileSync(newUrl.tempFilePath, 'base64');
                                    this.onUpdatePhoto(base64, fileName)
                                    // this.formValue.photoData = 'data:image/jpeg;base64,' + fileSystemManager.readFileSync(newUrl.tempFilePath, 'base64');
                                })
                            },
                            fail(err) {

                            }
                        })
                    } else {
                        let base64 = 'data:image/jpeg;base64,' + fileSystemManager.readFileSync(url, 'base64');
                        this.onUpdatePhoto(base64, fileName)
                        // 大小符合
                        // this.formValue.photoData = 'data:image/jpeg;base64,' + fileSystemManager.readFileSync(url, 'base64');
                        // this.fileBase64 = 'data:image/jpeg;base64,' + fileSystemManager.readFileSync(url, 'base64');

                    }
                },
            })
        },
        // 下拉选择数据
        confirmSelect({ value }) {
            console.log(value[0].code,value, "---136")
            updateSysPerson({[this.editDataIndex]:value[0].code}).then(res=>{
                notificationFun("修改成功")
                this.onGetUserInfo()
                this.showSelect = 0
            })
        },
        // 选择时间
        onSelectTime({value}) {
            updateSysPerson({["birthday"]:moment(value).format("YYYY-MM-DD")}).then(res=>{
                notificationFun("修改成功")
                this.onGetUserInfo()
                this.editVisable=false
            })
            this.calendarVisable = false
        },
        // input保存
        onSumitInput(){
            console.log(this.editInputData,"---293")
            updateSysPerson({[this.editDataIndex]:this.editInputData}).then(res=>{
                notificationFun("修改成功")
                this.onGetUserInfo()
                this.editVisable=false
            })
        },
        // 修改头像接口
        onUpdatePhoto(base64,fileName){
            updatePhoto({ base64 ,fileName}).then(res => {
                this.fileBase64=base64;
                notificationFun("修改成功")
                this.onGetUserInfo()
            })
        },
        // 格式月份
        formatter(type, value) {
                if (type === 'year') {
                    return `${value}年`
                }
                if (type === 'month') {
                    return `${value}月`
                }
                if (type === 'day') {
                    return `${value}日`
                }
                return value
            },
    },
    onReady() {
			// 微信小程序需要用此写法
			this.$refs.datetimePicker.setFormatter(this.formatter)
		},
    onLoad(){
        // 初始化dict
        this.onGetDict()
        // 初始化信息
        this.onGetUserInfo()
    },
    computed: {
        getTx() {
            return this?.formDate?.studentInfo?.avatar?this.formDate.studentInfo.avatar:"../../static/images/user/tx.svg"
        }
    },

}
</script>

<style lang="scss">
.infoItem {
    padding: 40rpx 30rpx 40rpx 40rpx;
    background-color: #fff;

}

.labelStyle {
    font-size: 32rpx;
    color: #666666;
    margin-right: 110rpx;
    min-width: 128rpx;
    display: inline-block;
}

.editBtn {
    color: #fff;
    border: 1px solid #4DC38585;
    background: linear-gradient(90deg, #37B874 0%, #B7F5D4 100%);
    width: 120rpx;
    height: 60rpx;
    border-radius: 24rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}
.editWrap{
    height: 100vh;
    background-color: #fff;
    padding: 0 30rpx;
    .myInputWrap{
        margin-top: 60rpx;
        margin-bottom: 100rpx;
    }
}
.user-avatar{
	margin-right: 0;
	margin-left: 0;
	padding: 0;
	border-radius: 0;
	background-color: transparent;
    width: 100%;
	&::after{
		border: none;
	}
}
</style>